<template>
  <div class="log-container">
    <el-card class="box-card">
      <!-- 搜索区域 -->
      <search-form
        v-model="queryParams"
        @search="handleQuery"
        @reset="handleReset"
      >
        <el-form-item label="用户名">
          <el-input
            v-model="queryParams.username"
            placeholder="请输入用户名"
            clearable
            @keyup.enter="handleQuery"
          />
        </el-form-item>
        <el-form-item label="状态">
          <el-select
            v-model="queryParams.status"
            placeholder="请选择状态"
            clearable
          >
            <el-option label="成功" value="1" />
            <el-option label="失败" value="0" />
          </el-select>
        </el-form-item>
        <el-form-item label="登录时间">
          <el-date-picker
            v-model="queryParams.timeRange"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            value-format="YYYY-MM-DD"
          />
        </el-form-item>
      </search-form>

      <!-- 操作按钮区域 -->
      <div class="toolbar-wrapper">
        <div class="left">
          <el-button
            type="danger"
            :disabled="selectedIds.length === 0"
            @click="handleBatchDelete"
          >
            <el-icon><Delete /></el-icon>
            批量删除
          </el-button>
          <el-button type="warning" @click="handleClear">
            <el-icon><Delete /></el-icon>
            清空
          </el-button>
          <el-button type="success" @click="handleExport">
            <el-icon><Download /></el-icon>
            导出
          </el-button>
        </div>
        <div class="right">
          <el-button type="primary" @click="handleRefresh">
            <el-icon><RefreshRight /></el-icon>
            刷新
          </el-button>
        </div>
      </div>

      <!-- 表格区域 -->
      <el-table
        v-loading="loading"
        :data="logList"
        :height="tableHeight"
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column label="序号" type="index" width="50" align="center" />
        <el-table-column
          label="用户名"
          prop="username"
          min-width="120"
          show-overflow-tooltip
        />
        <el-table-column label="登录地址" min-width="200" show-overflow-tooltip>
          <template #default="{ row }">
            <span>{{ row.ip }}</span>
            <el-tag size="small" type="info" class="ml-2">{{
              row.location
            }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column
          label="浏览器"
          prop="browser"
          min-width="120"
          show-overflow-tooltip
        />
        <el-table-column
          label="操作系统"
          prop="os"
          min-width="120"
          show-overflow-tooltip
        />
        <el-table-column label="登录状态" align="center" width="100">
          <template #default="{ row }">
            <el-tag :type="row.status ? 'success' : 'danger'">
              {{ row.status ? "成功" : "失败" }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column
          label="提示信息"
          prop="message"
          min-width="200"
          show-overflow-tooltip
        />
        <el-table-column label="登录时间" min-width="160" show-overflow-tooltip>
          <template #default="{ row }">
            {{ formatDateTime(row.createTime) }}
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页区域 -->
      <pagination
        v-model:page="queryParams.pageNum"
        v-model:limit="queryParams.pageSize"
        :total="total"
        @pagination="getLogList"
      />
    </el-card>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, onBeforeUnmount } from "vue";
import { Delete, Download, RefreshRight } from "@element-plus/icons-vue";
import { ElMessage, ElMessageBox } from "element-plus";
import { formatDateTime } from "@/utils/date";
import {
  getLoginLogPageList,
  batchDeleteLoginLog,
  clearLoginLog,
  exportLoginLog,
} from "@/api/system/loginLog";
import SearchForm from "@/components/base/SearchForm.vue";
import Pagination from "@/components/base/Pagination.vue";
import type { LoginLog } from "@/types/loginLog";

// 查询参数
const queryParams = reactive({
  pageNum: 1,
  pageSize: 10,
  username: "",
  status: "",
  timeRange: [] as string[],
});

// 数据相关
const loading = ref(false);
const logList = ref<LoginLog[]>([]);
const total = ref(0);
const selectedIds = ref<number[]>([]);

// 获取日志列表
const getLogList = async () => {
  loading.value = true;
  try {
    const { data } = await getLoginLogPageList({
      pageNum: queryParams.pageNum,
      pageSize: queryParams.pageSize,
      username: queryParams.username,
      status: queryParams.status,
      beginTime: queryParams.timeRange?.[0],
      endTime: queryParams.timeRange?.[1],
    });
    logList.value = data.records;
    total.value = data.total;
  } catch (error: any) {
    console.error("获取日志列表失败:", error);
    ElMessage.error(error.message || "获取日志列表失败");
  } finally {
    loading.value = false;
  }
};

// 搜索方法
const handleQuery = () => {
  queryParams.pageNum = 1;
  getLogList();
};

// 重置方法
const handleReset = () => {
  queryParams.username = "";
  queryParams.status = "";
  queryParams.timeRange = [];
  handleQuery();
};

// 选择项变化
const handleSelectionChange = (selection: LoginLog[]) => {
  selectedIds.value = selection.map((item) => item.id);
};

// 批量删除
const handleBatchDelete = async () => {
  if (selectedIds.value.length === 0) {
    ElMessage.warning("请选择要删除的记录");
    return;
  }

  try {
    await ElMessageBox.confirm("是否确认删除选中的日志数据?", "警告", {
      type: "warning",
      confirmButtonText: "确定",
      cancelButtonText: "取消",
    });
    await batchDeleteLoginLog(selectedIds.value);
    ElMessage.success("删除成功");
    getLogList();
  } catch (error: any) {
    if (error !== "cancel") {
      ElMessage.error(error.message || "删除失败");
    }
  }
};

// 清空日志
const handleClear = async () => {
  try {
    await ElMessageBox.confirm("是否确认清空所有日志数据?", "警告", {
      type: "warning",
      confirmButtonText: "确定",
      cancelButtonText: "取消",
    });
    await clearLoginLog();
    ElMessage.success("清空成功");
    getLogList();
  } catch (error: any) {
    if (error !== "cancel") {
      ElMessage.error(error.message || "清空失败");
    }
  }
};

// 导出日志
const handleExport = async () => {
  try {
    const params = {
      username: queryParams.username,
      status: queryParams.status,
      beginTime: queryParams.timeRange?.[0],
      endTime: queryParams.timeRange?.[1],
    };

    const response = await exportLoginLog(params);

    // 从响应头中获取文件名
    const contentDisposition = response.headers?.["content-disposition"];
    let filename = "登录日志.xlsx";
    if (contentDisposition) {
      const filenameMatch = contentDisposition.match(/filename=(.*?)(;|$)/);
      if (filenameMatch) {
        filename = decodeURIComponent(filenameMatch[1]);
      }
    }

    // 创建Blob对象并下载
    const blob = new Blob([response], { type: "application/vnd.ms-excel" });
    const url = window.URL.createObjectURL(blob);
    const link = document.createElement("a");
    link.href = url;
    link.download = filename;
    document.body.appendChild(link);
    link.click();
    document.body.removeChild(link);
    window.URL.revokeObjectURL(url);

    ElMessage.success("导出成功");
  } catch (error: any) {
    console.error("导出失败:", error);
    ElMessage.error(error.message || "导出失败");
  }
};

// 刷新列表
const handleRefresh = () => {
  getLogList();
};

// 表格高度自适应
const tableHeight = ref(500);

const calculateTableHeight = () => {
  const windowHeight = window.innerHeight;
  const otherHeight = 300;
  tableHeight.value = windowHeight - otherHeight;
};

onMounted(() => {
  getLogList();
  calculateTableHeight();
  window.addEventListener("resize", calculateTableHeight);
});

onBeforeUnmount(() => {
  window.removeEventListener("resize", calculateTableHeight);
});
</script>

<style lang="scss" scoped>
.log-container {
  height: 100%;

  .box-card {
    height: 100%;
    display: flex;
    flex-direction: column;

    :deep(.el-card__body) {
      flex: 1;
      overflow: hidden;
      display: flex;
      flex-direction: column;
    }
  }

  .toolbar-wrapper {
    padding: 16px 0;
    display: flex;
    justify-content: space-between;
    align-items: center;
  }

  .el-table {
    flex: 1;
  }

  .pagination-container {
    margin-top: 20px;
    display: flex;
    justify-content: flex-end;
  }

  .ml-2 {
    margin-left: 8px;
  }
}

// 响应式布局
@media screen and (max-width: 768px) {
  .log-container {
    .el-table {
      :deep(.el-table__cell) {
        padding: 8px 0;
      }
    }

    .pagination-container {
      :deep(.el-pagination) {
        .el-pagination__sizes {
          display: none;
        }
      }
    }
  }
}
</style>
